package com.zzq.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzq.account.dao.AccountDao;
import com.zzq.account.entities.po.AccountPO;
import com.zzq.account.entities.po.converter.AccountConverter;
import com.zzq.account.service.AccountService;
import com.zzq.account.entities.dto.AccountDTO;
import com.zzq.account.validator.ValidationResult;
import com.zzq.account.validator.ValidatorImpl;
import com.zzq.common.exception.BusinessException;
import com.zzq.common.exception.EmBusinessError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zzq
 * @date 2020/4/10 8:19 下午
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AccountConverter accountConverter;

    @Autowired
    private ValidatorImpl validator;

    @Override
    public AccountDTO selectByCode(String accountCode) {
        QueryWrapper<AccountPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_code", accountCode);
        AccountPO accountPO = accountDao.selectOne(queryWrapper);
        return accountConverter.toAccountDTO(accountPO);
    }

    @Override
    public void updateAccount(AccountDTO accountDTO) {
        AccountPO accountPO = accountConverter.toAccountPO(accountDTO);
        accountDao.updateById(accountPO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AccountDTO insertAccount(AccountDTO accountDTO) throws BusinessException {
        // 参数校验
        ValidationResult validate = validator.validate(accountDTO);
        if (validate.isHasErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, validate.getErrMsg());
        }

        // 保存到数据库
        AccountPO accountPO = accountConverter.toAccountPO(accountDTO);
        accountDao.insert(accountPO);

        return accountConverter.toAccountDTO(accountPO);
    }

    @Override
    public int deleteAccount(String accountCode) {
        QueryWrapper<AccountPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_code", accountCode);
        return accountDao.delete(queryWrapper);
    }
}
